﻿using IdGen;
using KWT.DRG_DIP.API.Infrastructure;
using KWT.DRG_DIP.Common;
using KWT.DRG_DIP.DB;
using KWT.DRG_DIP.DO.System;
using KWT.DRG_DIP.DTO.Basic.PolicyEnum;
using KWT.DRG_DIP.PO.Basic;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using OfficeOpenXml;
using EFCore.BulkExtensions;
using System.Diagnostics;
using Microsoft.AspNetCore.Authorization;
using Yitter.IdGenerator;
using System;

namespace KWT.DRG_DIP.API.Controllers.Basic
{
    /// <summary>
    /// 策略字典管理
    /// </summary>
    [ApiExplorerSettings(GroupName = "basic")]
    public class PolicyEnumController : BasicControllerBase
    {
        public EFContext ef { get; set; }

        /// <summary>
        /// 添加或修改
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public OutputResult AddOrUpdate(InAddOrUpdate dto)
        {
            if (string.IsNullOrEmpty(dto.SPID))
            {
                var policy = _mapper.Map<Sys_PolicyEnum>(dto);
                policy.SPID = "SP" + snow_id.CreateId().ToString();

                ef.Add(policy);
            }
            else
            {
                var policy = ef.Find<Sys_PolicyEnum>(dto.SPID);
                if (policy == null)
                {
                    return Fail("该项不存在！");
                }
                policy.Code1 = dto.Code1;
                policy.Code2 = dto.Code2;
                policy.Code3 = dto.Code3;
                policy.Name1 = dto.Name1;
                policy.Name2 = dto.Name2;
                policy.Name3 = dto.Name3;
                policy.GrpCondition1 = dto.GrpCondition1;
                policy.GrpCondition2 = dto.GrpCondition2;
                policy.Extra1 = dto.Extra1;
                policy.Extra2 = dto.Extra2;
                policy.Extra3 = dto.Extra3;
                policy.UpdTime = DateTime.Now;
                ef.Attach(policy);
            }
            var flag = ef.SaveChanges() > 0;
            if (flag)
            {
                string tenantID = HttpContext.Request.Headers["TenantID"];
                RedisHelper.HDel("PolicyEnum-" + tenantID, dto.Group);
            }
            return Output(flag, "操作成功", "操作失败");
        }


        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="spIDs"></param>
        /// <returns></returns>
        [HttpGet]
        [ProducesResponseType(typeof(Output<string>), 200)]
        public OutputResult Del([FromQuery] string[] spIDs)
        {
            var enums = ef.Set<Sys_PolicyEnum>().Where(x => spIDs.Contains(x.SPID)).ToList();
            if (enums.Count == 0)
            {
                return Fail("数据未匹配！");
            }
            ef.RemoveRange(enums);
            var flag = ef.SaveChanges() > 0;
            if (flag)
            {
                string tenantID = HttpContext.Request.Headers["TenantID"];
                RedisHelper.HDel("PolicyEnum-" + tenantID, enums.First().Group);
            }
            return Output(flag, "操作成功", "操作失败");
        }

        /// <summary>
        /// 批量导入
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(Output<string>), 200)]
        public OutputResult Import(InUpload dto)
        {
            using var pkg = new ExcelPackage(dto.file.OpenReadStream());
            var worksheet = pkg.Workbook.Worksheets[0];
            var list = worksheet.Dimension.ToCollection<Sys_PolicyEnum>();
            var idGeneratorOptions = new Yitter.IdGenerator.IdGeneratorOptions(1) { SeqBitLength = 10 };

            YitIdHelper.SetIdGenerator(idGeneratorOptions);
            list.ForEach(x =>
            {
                x.SPID = "SP" + YitIdHelper.NextId().ToString();
                x.Group = dto.Group;
            });
            ef.AddRange(list);
            var flag = ef.SaveChanges() > 0;
            if (flag)
            {
                string tenantID = HttpContext.Request.Headers["TenantID"];
                RedisHelper.HDel("PolicyEnum-" + tenantID, dto.Group);
            }
            return Output(flag, "操作成功", "操作失败");
        }

        /// <summary>
        /// 主手术（模糊查询）
        /// </summary>
        /// <param name="input">输入的文本</param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public OutputResult TopLike([FromQuery] string input)
        {
            var result = ef.Set<Sys_PolicyEnum>().Where(x => x.Group == "主手术" && (EF.Functions.Like(x.PinYin1, $"%{input}%")
            || EF.Functions.Like(x.Name1, $"%{input}%") || EF.Functions.Like(x.Code1, $"%{input}%")))
                .Select(x => new { code = x.Code1, name = x.Name1 })
                .Take(10).ToList();
            return Output(result != null, "", "", result);
        }

        /// <summary>
        /// 主诊断（模糊查询）
        /// </summary>
        /// <param name="input">输入的文本</param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public OutputResult TopLikeDiag([FromQuery] string input)
        {
            var result = ef.Set<Sys_PolicyEnum>().Where(x => x.Group == "主诊断" && (EF.Functions.Like(x.PinYin1, $"%{input}%")
            || EF.Functions.Like(x.Name1, $"%{input}%") || EF.Functions.Like(x.Code1, $"%{input}%")))
                .Select(x => new { code = x.Code1, name = x.Name1 })
                .Take(10).ToList();
            return Output(result != null, "", "", result);
        }

        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public OutputResult PageList(InPageList dto)
        {
            var q = ef.Set<Sys_PolicyEnum>().AsQueryable();
            if (!string.IsNullOrEmpty(dto.Group))
            {
                q = q.Where(x => x.Group == dto.Group);
            }
            if (!string.IsNullOrEmpty(dto.Code1))
            {
                q = q.Where(x => EF.Functions.Like(x.Code1, $"%{dto.Code1}%"));
            }
            if (!string.IsNullOrEmpty(dto.Code2))
            {
                q = q.Where(x => EF.Functions.Like(x.Code2, $"%{dto.Code2}%"));
            }
            if (!string.IsNullOrEmpty(dto.Code3))
            {
                q = q.Where(x => EF.Functions.Like(x.Code3, $"%{dto.Code3}%"));
            }
            if (!string.IsNullOrEmpty(dto.Name1))
            {
                q = q.Where(x => EF.Functions.Like(x.Name1, $"%{dto.Name1}%"));
            }
            if (!string.IsNullOrEmpty(dto.Name2))
            {
                q = q.Where(x => EF.Functions.Like(x.Name2, $"%{dto.Name2}%"));
            }
            if (!string.IsNullOrEmpty(dto.Name3))
            {
                q = q.Where(x => EF.Functions.Like(x.Name3, $"%{dto.Name3}%"));
            }
            if (!string.IsNullOrEmpty(dto.GrpCondition1))
            {
                q = q.Where(x => EF.Functions.Like(x.GrpCondition1, $"%{dto.GrpCondition1}%"));
            }
            if (!string.IsNullOrEmpty(dto.GrpCondition2))
            {
                q = q.Where(x => EF.Functions.Like(x.GrpCondition2, $"%{dto.GrpCondition2}%"));
            }

            int total = q.Count();
            var list = q.OrderBy(x => x.Sort).AsNoTracking().ToPageList(dto.PageNo, dto.PageSize);

            return Output(total > 0, "", "", new PageList<Sys_PolicyEnum>() { List = list, Total = total });
        }
    }
}
